import request from '@/utils/request'
import { getDictionaryDataSelector } from '@/api/systemData/dictionary'
import { 
  getAreaJurisdictionInfo,
  createAreaJurisdiction,
  updateAreaJurisdiction,
  checkAreaJurisdictionDuplicate,
  getProvinceList,
  getCityList
} from '@/api/campus/areaJurisdiction'

export default {
  data() {
    return {
      visible: false,
      isDetail: false,
      dataForm: {
        id: undefined,
        areaCode: undefined,
        areaName: undefined,
        provinceId: undefined,
        provinceName: undefined,
        cityId: null,
        cityName: undefined,
        priority: 10,
        enabledMark: 1,
        sortCode: 0,
        description: undefined
      },
      areaOptions: [],
      provinceOptions: [],
      cityOptions: [],
      rules: {
        areaCode: [
          { required: true, message: '请选择管理区域', trigger: 'change' }
        ],
        provinceId: [
          { required: true, message: '请选择省份', trigger: 'change' }
        ],
        priority: [
          { required: true, message: '请输入优先级', trigger: 'blur' },
          { type: 'number', min: 0, max: 100, message: '优先级必须在0-100之间', trigger: 'blur' }
        ],
        enabledMark: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ],
        sortCode: [
          { type: 'number', min: 0, message: '排序码必须大于等于0', trigger: 'blur' }
        ],
        description: [
          { max: 500, message: '描述不能超过500个字符', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.getAreaOptions()
    this.getProvinceOptions()
  },
  methods: {
    init(id, isDetail = false) {
      this.visible = true
      this.isDetail = isDetail
      this.dataForm.id = id || undefined
      
      this.$nextTick(() => {
        this.$refs.elForm.resetFields()
        if (this.dataForm.id) {
          this.getInfo()
        } else {
          // 新增时的默认值
          this.dataForm = {
            id: undefined,
            areaCode: undefined,
            areaName: undefined,
            provinceId: undefined,
            provinceName: undefined,
            cityId: null,
            cityName: undefined,
            priority: 10,
            enabledMark: 1,
            sortCode: 0,
            description: undefined
          }
        }
      })
    },
    getInfo() {
      getAreaJurisdictionInfo(this.dataForm.id).then(res => {
        this.dataForm = {
          ...this.dataForm,
          ...res.data
        }
        
        // 如果有省份，加载对应的城市选项
        if (this.dataForm.provinceId) {
          this.handleProvinceChange(this.dataForm.provinceId)
        }
      })
    },
    getAreaOptions() {
      getDictionaryDataSelector('MANAGEMENT_AREA').then(res => {
        this.areaOptions = res.data.list
      })
    },
    getProvinceOptions() {
      getProvinceList().then(res => {
        this.provinceOptions = res.data || []
      }).catch(() => {
        // 如果没有省份接口，使用模拟数据
        this.provinceOptions = [
          { id: '110000', fullName: '北京市' },
          { id: '120000', fullName: '天津市' },
          { id: '130000', fullName: '河北省' },
          { id: '140000', fullName: '山西省' },
          { id: '320000', fullName: '江苏省' },
          { id: '370000', fullName: '山东省' },
          { id: '610000', fullName: '陕西省' }
        ]
      })
    },
    handleAreaChange(areaCode) {
      const selectedArea = this.areaOptions.find(item => item.enCode === areaCode)
      this.dataForm.areaName = selectedArea ? selectedArea.fullName : undefined
    },
    handleProvinceChange(provinceId) {
      const selectedProvince = this.provinceOptions.find(item => item.id === provinceId)
      this.dataForm.provinceName = selectedProvince ? selectedProvince.fullName : undefined
      
      // 清空城市选择
      this.dataForm.cityId = null
      this.dataForm.cityName = undefined
      this.cityOptions = []
      
      if (provinceId) {
        getCityList(provinceId).then(res => {
          this.cityOptions = res.data || []
        }).catch(() => {
          // 如果没有城市接口，使用模拟数据
          if (provinceId === '320000') {
            this.cityOptions = [
              { id: '320100', fullName: '南京市' },
              { id: '320300', fullName: '徐州市' },
              { id: '320500', fullName: '苏州市' }
            ]
          } else if (provinceId === '140000') {
            this.cityOptions = [
              { id: '140100', fullName: '太原市' },
              { id: '140200', fullName: '大同市' }
            ]
          }
        })
      }
    },
    handleCityChange(cityId) {
      if (cityId) {
        const selectedCity = this.cityOptions.find(item => item.id === cityId)
        this.dataForm.cityName = selectedCity ? selectedCity.fullName : undefined
      } else {
        this.dataForm.cityName = undefined
      }
    },
    dataFormSubmit() {
      this.$refs.elForm.validate((valid) => {
        if (valid) {
          // 数据验证
          this.validateData().then(isValid => {
            if (!isValid) {
              return
            }
            
            // 显示加载状态
            const loading = this.$loading({
              target: this.$el,
              text: '保存中...'
            })
            
            const apiCall = this.dataForm.id 
              ? updateAreaJurisdiction(this.dataForm.id, this.dataForm)
              : createAreaJurisdiction(this.dataForm)
            
            apiCall.then(res => {
              loading.close()
              this.$message({
                type: 'success',
                message: res.msg || '操作成功',
                onClose: () => {
                  this.visible = false
                  this.$emit('refresh')
                }
              })
            }).catch(error => {
              loading.close()
              this.$message({
                type: 'error',
                message: error.msg || '操作失败，请重试'
              })
            })
          })
        } else {
          this.$message({
            type: 'error',
            message: '请检查表单填写是否正确'
          })
        }
      })
    },
    async validateData() {
      try {
        // 业务逻辑验证
        if (!this.dataForm.areaCode) {
          this.$message({
            type: 'error',
            message: '请选择管理区域'
          })
          return false
        }
        
        if (!this.dataForm.provinceId) {
          this.$message({
            type: 'error',
            message: '请选择省份'
          })
          return false
        }
        
        // 检查优先级范围
        if (this.dataForm.priority < 0 || this.dataForm.priority > 100) {
          this.$message({
            type: 'error',
            message: '优先级必须在0-100之间'
          })
          return false
        }
        
        // 检查是否存在重复配置
        const checkData = {
          areaCode: this.dataForm.areaCode,
          provinceId: this.dataForm.provinceId,
          cityId: this.dataForm.cityId,
          id: this.dataForm.id
        }
        
        try {
          const res = await checkAreaJurisdictionDuplicate(checkData)
          if (res.data && res.data.isDuplicate) {
            this.$message({
              type: 'error',
              message: '该管理区域已配置相同的省市管辖范围，请检查后重新配置'
            })
            return false
          }
        } catch (error) {
          // 如果检查接口不存在或出错，记录警告但不阻止提交
          console.warn('重复性检查失败:', error)
        }
        
        return true
      } catch (error) {
        this.$message({
          type: 'error',
          message: '数据验证失败，请重试'
        })
        return false
      }
    }
  }
}